/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NET_TCPCLIENT_H_
#define NET_TCPCLIENT_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <cstdint>
#include <cstddef>
#include <string>
#include <event2/buffer.h>
#include <event2/bufferevent.h>
#include <UGame/Macros.h>

namespace UGame {
namespace Net {
	class TcpDispatcher;
	class TcpClientDelegate;

    class TcpClient
    {
	public:
		enum EventFlags
		{
			EF_READ = 0x1,
			EF_WRITE = 0x2
		};
		enum ShutdownHow
		{
			SH_READ = 0x1,
			SH_WRITE = 0x2
		};

		TcpClient(void);
		~TcpClient(void);

		void SetDelegate(TcpClientDelegate* _Delegate);
		bool Connect(TcpDispatcher* _Dispatcher, const std::string& _Host, int _Port);
		void Close(void);

		const std::string& GetErrorString(void) const { return _errorString; }
		int GetErrorCode(void) const { return _errorCode; }

		void Send(const std::uint8_t *_Data, std::size_t _Size);

		std::size_t GetReceivedSize(void);
		int Read(std::uint8_t *_Data, std::size_t _Size);
		int ReadPeek(std::uint8_t *_Data, std::size_t _Size);
		std::size_t ReadSkip(std::size_t _Size);

		void EnableReceive(bool _Enable);
		void EnableSend(bool _Enable);

		void Shutdown(int _How);
	private:
		void _OnError(void);

		static void _ReadCallback(struct bufferevent *, void *);
		static void _WriteCallback(struct bufferevent *, void *);
		static void _EventCallback(struct bufferevent *, short, void *);

		int _fd;
		struct bufferevent* _bev;
		TcpClientDelegate* _delegate;
		std::string _errorString;
		int _errorCode;
		volatile bool _fatalError;
		DISALLOW_COPY_AND_ASSIGN(TcpClient);
    };

}}

#endif // NET_TCPCLIENT_H_
